package com.yonyou.brigade.openapi.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yonyou.brigade.basic_init.enums.ChannelEnum;
import com.yonyou.brigade.basic_init.model.BriChannel;
import com.yonyou.brigade.basic_init.props.PropUtil;
import com.yonyou.brigade.basic_init.service.IBriChannelService;
import com.yonyou.brigade.basic_init.service.IUserCenterService;
import com.yonyou.brigade.facade.service.ISSOService;
import com.yonyou.brigade.third_parties.ctripBC.service.ICtripBCUserService;
import com.yonyou.brigade.third_parties.smectrip.service.ISmeCtripUserService;
import com.yonyou.ybzboot.starter.common.exception.BusinessException;
import com.yonyou.ybzboot.uc.dto.UcUserDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static com.yonyou.brigade.util.resultutil.HttpSendUtils.sendPost;

@RequestMapping("/open/brigade")
@Controller
public class SSOController {

    @Autowired
    @Qualifier("SSOServiceImpl")
    private ISSOService ssoService;

    @Autowired
    @Qualifier("ctripBCUserServiceImpl")
    private ICtripBCUserService ctripBCUserService;

    @Autowired
    @Qualifier("smeCtripUserServiceImpl")
    private ISmeCtripUserService smeCtripUserService;

    @Autowired
    @Qualifier("briChannelServiceImpl")
    private IBriChannelService briChannelService;

    @Autowired
    @Qualifier("userCenterServiceImpl")
    private IUserCenterService iUserCenterService;

    @Autowired
    private PropUtil propUtil;

    @Value("${ybz.baseUrl}")
    private String ybzBaseUrl;

    private Logger logger=LoggerFactory.getLogger(SSOController.class);

    @RequestMapping(value="/order", method=RequestMethod.GET)
    public @ResponseBody
    String  getSSOUrl(String clientId,String tenantId,String phone,String token,String third,String channel) {

        logger.info("tenantId:"+tenantId+",phone:"+phone+",third:"+third+",channel:"+channel);
        String url= ssoService.getSSOUrl(third, channel, phone, tenantId);
        return url;
    }



    /**
     * donghang 修改携程商旅登录方式，统一入口，不再读取报账里的ctrip_master和ctrip_sme_master库
     * @param tenantId
     * @param orgpk
     * @param initPage
     * @param phone
     * @param source
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "/ctrip/login" ,method = RequestMethod.GET )
    public void ctripLogin(@RequestParam String tenantId, String orgpk, String initPage, String phone, String source, int tokenType ,HttpServletResponse response) throws IOException {
        BriChannel briChannel = null;
        briChannel=briChannelService.getEnableChannelByPersonTenantOrgAndChannel(tenantId, orgpk, ChannelEnum.CTRIPBC.getName());
        // add by yangxw1 2021年10月18日 start
        //如果信息为空-查询用户的兼职组织，根据兼职组织查询商旅信息-如果都为空走系统逻辑
        UcUserDto ucUserDtoByPhoneTemp = iUserCenterService.listCompleteUcUserByUserMobiles4admin(phone, tenantId);
        if(briChannel == null){
            if (ucUserDtoByPhoneTemp != null) {
                //查询兼职组织
                String  userid = ucUserDtoByPhoneTemp.getUserId();
                List<String> partorg = queryUsePartOrg(userid,tenantId);
                boolean folt = false;
                for (String pk_org : partorg) {
                    if(folt){
                        continue;
                    }
                    briChannel = briChannelService.getEnableInfoByTenantOrg(tenantId, pk_org, ChannelEnum.CTRIPBC.getName());
                    folt = briChannel != null;
                }
            }else{
                logger.info("用户中心查无此人" + phone);
            }
        }
        // end
        if(briChannel != null){
            //携程大客户单点登录
            try {
                ctripBCUserService.getLoginInfo(tenantId,orgpk,phone,initPage,tokenType,response,briChannel , source);
            }
            catch (Exception e)
            {
                throw  new BusinessException(e.getMessage());
            }
        }else {
            briChannel=briChannelService.getEnableChannelByPersonTenantOrgAndChannel(tenantId, orgpk, ChannelEnum.CTRIPSME.getName());
            if( briChannel != null){
                //携程商旅通单点登录
                try {
                    smeCtripUserService.getLoginInfo(tenantId,orgpk,phone,initPage,source,response,briChannel);
                }
                catch (Exception e)
                {
                    throw  new BusinessException(e.getMessage());
                }
            }
        }
        if (briChannel == null) {
            //没有开通携程,直接跳转未开通界面
            response.sendRedirect(propUtil.getNO_ACCESS_URL());
        }
    }

    /**
     * 查询用户兼职组织 a
     * @param userId 友报账用户id
     * @param tenantId 租户id
     * @return
     */
    private  List<String> queryUsePartOrg(String userId,String tenantId){
        JSONObject param = new JSONObject();
        param.put("tenantId",tenantId);
        param.put("userId",userId);
        //POST=到NCC进行穿透
        String url = ybzBaseUrl+"/open/brigade/nodeRef/queryUsePartOrg";
        logger.error("友报账进行兼职组织查询--url:"+url+" paeam:"+param.toString());
        String NCCBriOrderListDTO = sendPost(url, param.toString());
        logger.error("NCC返回数据NCCBriOrderListDTO"+NCCBriOrderListDTO);
        List<String> userList = new ArrayList<>();
        if(!StringUtils.isEmpty(NCCBriOrderListDTO)){
            JSONObject sonobj =  JSONObject.parseObject(NCCBriOrderListDTO);
            String code = sonobj.getString("code");
            if(!StringUtils.isEmpty(sonobj)  && "0000".equals(code)){
                JSONObject data =  sonobj.getJSONObject("data");
                userList = data.getObject("usePartOrg",List.class);
            }
        }
        return userList;
    }
}


